import router from './router'
import {Message} from 'element-ui'
import {Route} from 'vue-router'
import Cookies from "js-cookie";
import store from './store'
import { use } from 'vue/types/umd';
import loginApi from "@/APIService/api/login";
import {supplayMenu,adminMenu} from '@/utils/common'

//白名单
const whiteList= ['/login']

router.beforeEach(async(to:Route,_:Route,next:any)=>{

    // 判断token
    if(Cookies.get("token")) {
        if(to.path === '/login') {
            next({path: '/'})
        }else{
            let userName = store.state.userInfo
            if(userName){
               next()
            }else{
                
                let res = await loginApi.getInfo()
                if(res.code === 20000){
                    sessionStorage.setItem("userInfo", JSON.stringify(res.data))
                    store.commit('updateUserInfo',res.data)
                    
                    if(store.state.roleMenList.length){
                        next()
                    }else{
                        store.state.userInfo.role === 'SUPPLIER'?router.addRoutes(supplayMenu):router.addRoutes(adminMenu)
                        store.state.userInfo.role === 'SUPPLIER'?store.commit('addMenuList',supplayMenu):store.commit('addMenuList',adminMenu)
                        next({ ...to, replace: true })
                    }
                   
                }else{
                    console.log(res.msg)
                }

            }

            // todo 重新获取信息 接口获取信息
            next()
        }

    }else{
        if (whiteList.indexOf(to.path) !== -1){
            // 白名单 直接通过
            next()
        }else{
            next(`/login?redirect=${to.path}`)
        }
    }
})
